#!/usr/bin/perl
#Programmer: Rory Carmichael
#Purpose: Summarize the contents of a group of thingies and stuff, you know, I know I know, Love Ya
#Usage: group_summary.pl <group_dir> <name_lut>

my %nlut;
my ($dir, $lut) = @ARGV;

open(LUT, $lut);
while (my $line = <LUT>) {
	chomp $line;
	my @splitline = split(/\t/, $line);
	if (exists($nlut{$splitline[-1]})) {
		die("Got a key collision :-(\n");
	}
	my $annot = $splitline[0];
	$annot =~ s/>//;
	$annot =~ s/\s/_/g;
	$nlut{$splitline[1]} = $annot;
}
close(LUT);

print "CLUSTER\tSEQS\tORGS\tNUM_SEQS\tNUM_ORGS\tMIN_GAPS\tMAX_GAPS\tMEAN_GAPS\tGAPS_PER_BASE\tSEQUENCE_LENGTH\n";
foreach my $file (`ls $dir`) {
	my $cluster = [split(/\./, $file)]->[0];
	my @alignment = `cat $dir/$file`;
	my @seqs = ();
	my @annots = ();
	my %orgs;
	my $mean_dash = 0;
	my $min_dash;
	my $max_dash;
	my $seq_len = 0;
	foreach my $line (@alignment) {
		chomp $line;
		if ($line =~ /^>/) {
			$line =~ s/>//;
			push(@seqs, $line);
			push(@annots, $nlut{$line});
			my $org = [split(/\|/, $line)]->[0];
			$orgs{$org} = 1;
		} else {
			if((length($line) != $seq_len) && ($seq_len != 0)) {
				die("Inconsistent line lengths detected for $cluster\n");
			}
			$seq_len = length($line);
#			print "\n\n$line\n***\n";
			$line =~ s/[^-]//g;
#			print "$line\n";
			if(!defined($min_dash) && !defined($max_dash)) {
				$min_dash = length($line);
				$max_dash = length($line);
			} else {
				$min_dash = length($line) if length($line) < $min_dash;
				$max_dash = length($line) if length($line) >= $max_dash;
			}
			$mean_dash += length($line);
		}
	}
	my $org_cnt = scalar(keys(%orgs));
	my $num_seqs = scalar(@seqs);
	$mean_dash = $mean_dash/($num_seqs);
	my $num_orgs = scalar(keys(%orgs));
	my $dash_dens = $mean_dash/$seq_len;
	print "$cluster\t" . join(",", @seqs) . "\t" . join(",",keys(%orgs)) . "\t" . join(",",@annots) . "\t$num_seqs\t$num_orgs\t$min_dash\t$max_dash\t$mean_dash\t$dash_dens\t$seq_len\n";
}
